<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 祀念网络科技有限公司 [ http://www.sinian.com ]
// +----------------------------------------------------------------------
// | 官方网站: 暂无
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | 联系人: 王艳峰：13653680820
// +----------------------------------------------------------------------

namespace app\data\controller\control;
use app\data\model\ControlPlanItemModel;
use app\data\model\ControlPlanListModel;
use app\data\model\ControlPlanModel;
use think\admin\Controller;
use think\facade\Db;

/**
 * 合并计划管理
 * Class PlanApply
 * @package app\auditing\controller
 */
class PlanMerge extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'sn_control_plan_merge';

    /**
     * 材料提交管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '合并计划管理';
        $admin_user = session('user');
        $query = $this->_query($this->table)->equal('status')->like('admin_name,admin_nickname,title')->alias('m');
        if($admin_user['authorize'] == 2){
            $query->where('m.admin_id',$admin_user['id']);
            $query->join('system_user u','m.admin_id = u.id');
        }else{
            $query->where('m.below_admin_id',$admin_user['id'])->whereOr('m.plan_status','>=',$admin_user['authorize']);
            $query->join('system_user u','m.below_admin_id = u.id');
        }
        $this->assign('authorize',$admin_user['authorize']);
        $query->order('m.id desc')->field('m.*')->page();
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as $k=>$v){
            $data[$k]['below_admin_name'] = Db::name('system_user')->where('id',$v['below_admin_id'])->value('username');
            $data[$k]['integration_time'] = Db::name('sn_control_plan_integration')->where('id',$v['integration_id'])->value('create_at');
        }
    }
    /**
     * 详情
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function detail()
    {
        $this->title = '详情';
        $data = input('get.');
        $where = array( 'id'=>$data['id']);
        $info = Db::name($this->table)->where($where)->find();
        $this->assign('info',$info);
        $plan_list = ControlPlanListModel::whereIn('plan_id',$info['plan_ids'])->group('material_code')->field('*,sum(material_num) as material_num')->order('material_code')->select()->toArray();
        $total = 0;
        foreach ($plan_list as $k=>$v){
            $plan_list[$k]['info'] = ControlPlanListModel::where(['material_code'=>$v['material_code']])->whereIn('plan_id',$info['plan_ids'])->field('merge_id,material_code,admin_name,sum(material_num) as material_num')->order('material_code')->column('admin_name,material_num');
            $plan_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['material_price'] * $v['material_num']);
            $total += sprintf("%01.2f", $v['material_price'] * $v['material_num']);
        }
        $this->assign('plan_list',$plan_list);
        $this->assign('total',$total);
        $this->fetch();
    }

    /**
     * 审核通过
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function to_examine()
    {
        $this->title = '审核通过';
        $this->_form($this->table, 'to_examine');

    }


    /**
     * 审核拒绝
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function refusal()
    {
        $adminUser = session('user');
        $merge_id = input('id');
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $plan_ids = ControlPlanModel::where('merge_id',$merge_id)->column('id');
        foreach ($plan_ids as $k=>$v){
            $saveArr[$k]['status'] = -1;
            $saveArr[$k]['time'] = $dateTime;
            $saveArr[$k]['to_reason'] = $refusal_cause;
            $saveArr[$k]['collect_id'] = $v;
            $saveArr[$k]['admin_id'] = $adminUser['id'];
            $saveArr[$k]['admin_name'] = $adminUser['username'];
            $saveArr[$k]['admin_authorize'] = $adminUser['authorize'];
            $saveArr[$k]['admin_nickname'] = $adminUser['nickname'];
        }
        //开启事务
        Db::startTrans();
        try{
            $ControlPlanItemModel = new ControlPlanItemModel();
            $plan_item = $ControlPlanItemModel->saveAll($saveArr);
            if (!$plan_item) {$this->error('服务器错误');}
            //批量修改主表计划
            $plan_list = ['status' => '-1','reason_name'=>$adminUser['username'],'reason_id'=>$adminUser['id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime,'merge_id'=>0];
            $plan_save = ControlPlanModel::whereIn('id',$plan_ids)->update($plan_list);
            if (!is_int($plan_save)) {$this->error('服务器错误');}
            //批量修改子表计划
            $plan_zi_save = ControlPlanListModel::whereIn('plan_id',$plan_ids)->update(['merge_id'=>0]);
            if (!is_int($plan_zi_save)) {$this->error('服务器错误');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $save_data = ['status' => '-1','reason_name'=>$adminUser['username'],'reason_id'=>$adminUser['id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime];
        $this->_save($this->table, $save_data);
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        $admin_user = session('user');
        if ($this->request->isPost()){
            if(!$data['plan_status']){$this->error('请先选择下级审批权限');}
            if(!$data['below_admin_id']){$this->error('请先选择下级审批人');}
            //开启事务
            Db::startTrans();
            try{
                //修改流程表信息
                $plan_ids = ControlPlanListModel::where('merge_id',$data['id'])->group('plan_id')->column('plan_id');
                foreach ($plan_ids as $k=>$v){
                    $saveArr[$k]['status'] = 1;
                    $saveArr[$k]['time'] = date('Y-m-d H:i:s');
                    $saveArr[$k]['to_reason'] = $data['remarks'];
                    $saveArr[$k]['collect_id'] = $v;
                    $saveArr[$k]['admin_id'] = $admin_user['id'];
                    $saveArr[$k]['admin_name'] = $admin_user['username'];
                    $saveArr[$k]['admin_authorize'] = $admin_user['authorize'];
                    $saveArr[$k]['admin_nickname'] = $admin_user['nickname'];
                }
                $ControlPlanItemModel = new ControlPlanItemModel();
                $plan_item = $ControlPlanItemModel->saveAll($saveArr);
                if(!$plan_item){$this->error('服务器错误');}
                if($admin_user['authorize'] == 2){
                    $data['examine_admin_id'] = $admin_user['id'];
                }
                // 执行提交操作
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());
            }
        }
        $this->list = Db::name('system_user')->where('authorize',$data['plan_status']+1)->where('is_deleted',0)->field('id,nickname,username')->select()->toArray();
        $this->auth_list = Db::name('system_auth')->where('status',1)->where('sort','>',$admin_user['authorize'])->select()->toArray();
    }

    /**
     * 获取下级审批人信息
     */
    public function getParentInfo()
    {
        $id = input('id');
        $info = Db::name('system_user')->where(['status' => 1])->where('authorize','=',$id)->where('is_deleted',0)->field('id,username,nickname')->select();
        return $info;
    }

    public function deep_in_array($value, $array) {
        foreach($array as $item) {
            if(!is_array($item)) {
                if ($item == $value) {
                    return true;
                } else {
                    continue;
                }
            }
            if(in_array($value, $item)) {
                return true;
            } else if(deep_in_array($value, $item)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 明细
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function detail_zi()
    {
        $this->title = '明细';
        $data = input('get.');
        $where = array( 'id'=>$data['id']);
        $info = Db::name($this->table)->where($where)->find();
        $plan_list = Db::name('sn_control_plan_list')->where(['material_code'=>$data['material_code']])->whereIn('plan_id',$info['plan_ids'])->field('*,sum(material_num) as material_num')->group('admin_id')->order('material_code desc')->select()->toArray();
        foreach ($plan_list as $k=>$v){
            $plan_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['material_price'] * $v['material_num']);
        }
        $this->assign('plan_list',$plan_list);
        $this->fetch();
    }

    /**
     * 计划明细
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function plan_log()
    {
        $this->title = '计划明细';
        $data = input('get.');
        $where = array( 'id'=>$data['id']);
        $info = Db::name($this->table)->where($where)->order('id desc')->value('plan_ids');
        if(!$info){$this->error('该计划不属于合并计划');}
        $planList = ControlPlanModel::whereIn('id',$info)->order('id desc')->select()->toArray();
        foreach ($planList as $k=>$v){
            $planList[$k]['plan_list'] = ControlPlanListModel::where('plan_id',$v['id'])->order('material_code')->select()->toArray();
            $planList[$k]['table'] = 0;
            foreach ($planList[$k]['plan_list'] as $key => $val){
                $planList[$k]['plan_list'][$key]['material_xjprice'] = sprintf("%01.2f", $val['material_price'] * $val['material_num']);
                $planList[$k]['table'] += sprintf("%01.2f", $val['material_price'] * $val['material_num']);
            }
        }
        $this->assign('plan_list',$planList);
        $this->fetch();
    }
    /**
     * 计划整合
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function merge()
    {
        $data = input('post.');
        $idArr = explode(',',$data['id']);
        if(count($idArr) == 1){$this->error('请选择两个或两个以上整合');}
        $dateTime = date('Y-m-d H:i:s',time());
        $adminUser = session('user');
        $addAr = array(
            'title'=>date('Y年m月d日',time()).'计划整合',
            'merge_ids'=>$data['id'],
            'admin_id'=>$adminUser['id'],
            'admin_name'=>$adminUser['username'],
            'admin_nickname'=>$adminUser['nickname'],

        );
        //开启事务
        Db::startTrans();
        try{
            $plan_integration_id = Db::name('sn_control_plan_integration')->insertGetId($addAr);
            if(!$plan_integration_id){$this->error('服务器错误，请重试~');}
            $plan_merge = Db::name('sn_control_plan_merge')->whereIn('id',$idArr)->update(['integration_id'=>$plan_integration_id]);
            if(!$plan_merge){$this->error('服务器错误，请重试~');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据整合成功');
    }

    /**
     * 删除计划信息
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $id = input('post.id');
        //开启事务
        Db::startTrans();
        try{
            if(ControlPlanModel::where('merge_id',$id)->count()){
                //还原合并数据
                $plan_apply_merge_id = ControlPlanModel::where('merge_id',$id)->update(['merge_id'=>0]);
                if(!$plan_apply_merge_id){$this->error('服务器错误，请重试~');}
                $planList = ControlPlanListModel::where('merge_id',$id)->update(['merge_id'=>0]);
                if(!$planList){$this->error('服务器错误，请重试~');}
            }
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->_delete($this->table);
    }

}
